/*Copyright (c) 2010 Tiana RAZAFINDRALAMBO

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package;
import php.Lib;
class FB
{
	public static var params		:Hash<Dynamic>;
	public static var redirect_uri	:String;
	public static var facebook		:Facebook;
	public static var session		:Dynamic;
	private static var currentUID	:String;
	private static var currentUser	:Dynamic;
	private static var permissions	:Array<String>;
	private static var scope		:String;
		 
	public static function init(p:Hash<Dynamic>, appURI:String, perm:Array<String> = null):Dynamic
	{ 
		params 			= p;
		facebook 		= new Facebook(php.Lib.associativeArrayOfHash(params));
		
		redirect_uri 	= appURI; 
		
		permissions = perm;
		
		setScope();		
		
		session		 	= facebook.getSession(); 
		
		if(session)
		{
			if(codeIsSet())
			{
				currentUID 		= facebook.getUser();
				currentUser 	= facebook.api('/me');
			}
			else
			{
				redirect();
			}
		}
		else
		{
			redirect();
		}
		return session;
	} 
	public static function setScope()
	{ 
		scope  = ""; 
		if(permissions!=null)
		{
			var i  = 0;
			for(x in permissions)
			{
				i++;
				scope += x+((i<permissions.length)?",":""); 
			}
		}
	} 
	public static function getUser(user:String)
	{
		return php.Lib.hashOfAssociativeArray(facebook.api("/"+user));
	}
	public static function getUserFields(user:String, fields:Array<String>)
	{
		var str = "";
		var length = fields.length;
		var i = 0;
		for(f in fields)
		{
			i++;
			str +=f+((i<length)?",":""); 
		} 
		return php.Lib.hashOfAssociativeArray(facebook.api("/"+user+"?fields="+str));
	} 
	public static function sessionIsSet()
	{
		return (session!=null);
	}
	public static function getCurrentUser()
	{
		return php.Lib.hashOfAssociativeArray(currentUser);
	}
	public static function getCurrentUID()
	{
		return currentUID;
	}
    public static function codeIsSet():Bool
	{ 
		return php.Web.getParams().exists('code');
	}
	public static function redirect():Void
	{
		Lib.print("<script type=text/javascript>window.top.location.href='https://graph.facebook.com/oauth/authorize?client_id="+facebook.getAppId()+"&redirect_uri="+redirect_uri+"&scope="+scope+"';</script>");
	}
}


class Permissions
{
	/*PUBLISHING PERMISSIONS*/
	public static inline var PUBLISH_STREAM 		= "publish_stream";
	public static inline var CREATE_EVENT			= "create_event";
	public static inline var RSVP_EVENT				= "rsvp_event";
	public static inline var SMS					= "sms";
	public static inline var OFFLINE_ACCESS 		= "offline_access";
	
	/*DATA PERMISSIONS
	 * User permissions : */
	public static inline var ABOUT_ME				= "user_about_me";
	public static inline var ACTIVITIES				= "user_activities";
	public static inline var BIRTHDAY				= "user_birthday";
	public static inline var EDUCATION_HISTORY		= "user_education_history";
	public static inline var EVENTS					= "user_events";	
	public static inline var GROUPS					= "user_groups";
	public static inline var HOMETOWN				= "user_hometown";
	public static inline var INTERESTS				= "user_interests";			
	public static inline var LIKES					= "user_likes";
	public static inline var LOCATION				= "user_location";
	public static inline var NOTES					= "user_notes";
	public static inline var ONLINE_PRESENCE		= "user_online_presence";
	public static inline var PHOTO_VIDEO_TAGS		= "user_photo_video_tags";
	public static inline var PHOTOS					= "user_photos";
	public static inline var RELATIONSHIPS			= "user_relationships";
	public static inline var RELIGION_POLITICS		= "user_religion_politics";
	public static inline var STATUS					= "user_status";
	public static inline var VIDEOS					= "user_videos";
	public static inline var WEBSITE				= "user_website";
	public static inline var WORK_HISTORY			= "user_work_history";
	public static inline var EMAIL					= "email";
	public static inline var FRIENDLISTS			= "read_friendlists";
	public static inline var INSIGHTS				= "read_insights";
	public static inline var MAILBOX				= "read_mailbox";
	public static inline var REQUESTS				= "read_requests";
	public static inline var STREAM					= "read_stream";
	public static inline var XMPP_LOGIN				= "xmpp_login";
	public static inline var ADS_MANAGEMENT			= "ads_management";
	public static inline var CHECKINS				= "user_checkins";
	
	/*Friends permissions*/
	public static inline var F_ABOUT_ME				= "friends_about_me";
	public static inline var F_ACTIVITIES			= "friends_activities";
	public static inline var F_BIRTHDAY				= "friends_birthday";
	public static inline var F_EDUCATION_HISTORY	= "friends_education_history";
	public static inline var F_EVENTS				= "friends_events";	
	public static inline var F_GROUPS				= "friends_groups";
	public static inline var F_HOMETOWN				= "friends_hometown";
	public static inline var F_INTERESTS			= "friends_interests";			
	public static inline var F_LIKES				= "friends_likes";
	public static inline var F_LOCATION				= "friends_location";
	public static inline var F_NOTES				= "friends_notes";
	public static inline var F_ONLINE_PRESENCE		= "friends_online_presence";
	public static inline var F_PHOTO_VIDEO_TAGS		= "friends_photo_video_tags";
	public static inline var F_PHOTOS				= "friends_photos";
	public static inline var F_RELATIONSHIPS		= "friends_relationships";
	public static inline var F_RELIGION_POLITICS	= "friends_religion_politics";
	public static inline var F_STATUS				= "friends_status";
	public static inline var F_VIDEOS				= "friends_videos";
	public static inline var F_WEBSITE				= "friends_website";
	public static inline var F_WORK_HISTORY			= "friends_work_history"; 
	public static inline var F_CHECKINS				= "friends_checkins";
}

typedef MinDef =
{
	var id:String;
	var name:String;
}
typedef User =
{
	var id:String;
	var name:String;
	var first_name:String;
	var last_name:String;
	var link:String;
	var about:String;
	var birthday:String;
	var hometown:MinDef;
	var location:MinDef;
	var bio:String;
	var work:Array<WorkDef>;
	var education:Array<EducationDef>;
	var gender:String;
	var website:String;
	var timezone:Int;
	var locale:String;
	var verified:Bool;
	var updated_time:String;
}
typedef WorkDef = 
{
	var employer:MinDef;
	var location:MinDef;
	var position:MinDef;
	var start_date:String;
	var end_date:String;
	var description:String;
} 
typedef EducationDef = 
{
	var school:MinDef;
	var year:MinDef;
	var concentration:Array<MinDef>;
} 
extern class Facebook
{
    static function __init__():Void untyped{
        __call__("require", "facebook.php");
    }
	public function new(params:Dynamic):Void;
	public function setAppId(appId:String):String;
	public function getAppId():String;
	public function setApiSecret(apiSecret:String):String;
	public function getApiSecret():String;
	public function setCookieSupport(cookieSupport:Bool):Bool;
	public function setBaseDomain(domain:String):Dynamic;
	public function useCookieSupport():Bool;
	public function getBaseDomain():String;
	public function setFileUploadSupport(fileUploadSupport:String):String;
	public function useFileUploadSupport():String;
	public function getSignedRequest():String;
	public function setSession(session:Dynamic = null, write_cookie:Bool = true):Dynamic;
	public function getSession():Dynamic;
	public function getUser():String;
	public function getAccessToken():String;
	public function getLoginUrl(params:Dynamic):Void;
	public function getLogoutUrl(params:Dynamic):Void;
	public function getLoginStatusUrl(params:Dynamic):Void;
	public function api(?param:Dynamic):Dynamic;
}
